import { Component, ViewChild, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { AuthenticationService } from '../../service/auth.service';
import { MD5 } from '../../common/md5';
import { Toastr } from '../../common/toastr';

@Component({
    moduleId: module.id,
    templateUrl: "login.component.html"
})
export class LoginComponent implements OnInit {
    private viewModel = {
        userName: "admin",
        password: "123",
        isRemeberMe: false
    }
    private hasRemeberAccount: boolean;

    constructor(
        private authSvr: AuthenticationService,
        private router: Router
    ) { }

    ngOnInit() {
        let currentAccount = localStorage.getItem("account");
        if (currentAccount) {
            this.viewModel = JSON.parse(currentAccount);
            this.hasRemeberAccount = true;
        }
    }

    async loginBtn_click() {
        try {
            if (!this.hasRemeberAccount) this.viewModel.password = MD5.getHashCode(this.viewModel.password);
            if (this.viewModel.isRemeberMe) {
                localStorage.setItem("account", JSON.stringify(this.viewModel));
            }
            else {
                localStorage.removeItem("account");
            }
            await this.authSvr.Login(this.viewModel.userName, this.viewModel.password);
            this.router.navigate(['/main']);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    remeberMe_change() {
        this.viewModel.isRemeberMe = !this.viewModel.isRemeberMe;
    }
}